<template>
  <UploadExcel :onSuccess="onSuccess" />
</template>

<script setup>
import UploadExcel from '@/components/UploadExcel';
import { ElMessage } from 'element-plus';
import { USER_RELATIONS, formatDate } from './utils';
import { userBatchImport } from '@/api/user-manage';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';

const i18n = useI18n();
const router = useRouter();

const onSuccess = async ({ header, results }) => {
  const updateData = generateData(results);
  await userBatchImport(updateData);
  ElMessage.success(results.length + i18n.t('msg.excel.importSuccess'));
  router.push('/user/manage');
};

const generateData = (results) => {
  const arr = [];
  results.forEach((item) => {
    const userInfo = {};
    Object.keys(USER_RELATIONS).forEach((key) => {
      if (USER_RELATIONS[key] === 'openTime') {
        userInfo[key] = formatDate(item[USER_RELATIONS[key]]);
        return;
      }
      userInfo[USER_RELATIONS[key]] = item[key];
    });
    arr.push(userInfo);
  });
  return arr;
};
</script>
